/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-18 11:25:30
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-17 15:04:39
 * @FilePath: \project_keep\keep_motion_manger\src\main.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import './assets/main.css';

import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

import 'element-plus/dist/index.css';
// import '@/assets/light.css';
// import '@/assets/dark.css';

import App from './App.vue';
import router from './router';
import { installLayout } from '@/layouts/AdminLayout';

import { usePathStore } from '@/stores/paths';
import { useBreadcrumbStore } from '@/stores/breadcrumb';

const app = createApp(App);
app.use(createPinia());
app.use(router);
app.use(ElementPlus);
installLayout(app, {
  sidebarWidth: '240px',
  theme: 'light'
});
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
router.beforeEach((to, from, next) => {
  // 未登录时，只能访问登录页和注册页
  if (to.path === '/login' || to.path === '/register') next();
  const token = sessionStorage.getItem('token');
  if (!token) next('/login');
  const paths = usePathStore().path;
  // 检索所有路由路径
  if (paths.length === 0) next('/login');
  // 检查当前路由是否在权限列表中
  const childList = paths.flatMap(path => path.children.map(child => child.path));
  const parentList = paths.map(path => path.children? path.path : '');
  const allList = [...childList, ...parentList];
  if (!allList.includes(to.path)) next('/login');
  // 检查通过，继续导航
  // 设置面包屑
  const pathNameMap = paths.reduce((acc, path) => {
    acc[path.path] = path.meta.title;
    if (path.children) {
      path.children.forEach(child => {
        acc[child.path] = child.meta.title;
      });
    }
    return acc;
  }, {});
  const breadcrumbList = to.matched.map(item => ({
    path: item.path,
    title: pathNameMap[item.path] || '首页'
  }));
  useBreadcrumbStore().setBreadcrumb(breadcrumbList);
  next();
});

app.mount('#app');
